/*
 * @copyright IMTT. Co. Ltd.
 * Here is detailed Comment. 
 */
package com.suredy.base.realm;


import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.suredy.base.model.User;
import com.suredy.base.service.UserSrv;
import com.suredy.core.service.ApplicationContextHelper;



/**
 * @author ZhangMaoren
 * @copyright suredy. Co. Ltd.
 */
public class JDBCRealm extends AuthorizingRealm {

	
    

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userCode = (String)principals.getPrimaryPrincipal();
        UserSrv service = ApplicationContextHelper.getBeanByType(UserSrv.class); 
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(service.getRoles(userCode));
        authorizationInfo.setStringPermissions(service.getPermissions(userCode));

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws UnknownAccountException, IncorrectCredentialsException {
        String secureId = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        UserSrv service = ApplicationContextHelper.getBeanByType(UserSrv.class); 
        User user = service.getUser(secureId);
        if(user == null) {
            throw new UnknownAccountException();//没找到帐号
        }
        if (!password.equals(user.getPwd())) {
        	throw new IncorrectCredentialsException(); //密码错误
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUnitCode(), user.getPwd(), getName());
        return info;
        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配
       
//        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
//                user.getUserCode(), //用户名
//                user.getPwd(), //密码
//                ByteSource.Util.bytes(user.getUserCode()),//salt=username+salt
//                getName()  //realm name
//        );
//        return info;
    }
}
